package org.timeismoney.payment.web.action.teacher;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.timeismoney.payment.common.PageBean;
import org.timeismoney.payment.exception.BizException;
import org.timeismoney.payment.model.Item;
import org.timeismoney.payment.model.ItemUnitDetail;
import org.timeismoney.payment.model.SchoolYear;
import org.timeismoney.payment.service.ItemService;
import org.timeismoney.payment.service.ItemStuDetailService;
import org.timeismoney.payment.service.ItemUnitDetailService;
import org.timeismoney.payment.service.PaymentRecordService;
import org.timeismoney.payment.service.SchoolYearService;
import org.timeismoney.payment.service.UnitService;
import org.timeismoney.payment.web.WebUtils;
import org.timeismoney.payment.web.action.BaseAction;
import org.timeismoney.payment.web.form.ItemDetailForm;

public class AdminItem4UnitAction extends BaseAction {
	private static Logger			log	= Logger.getLogger(AdminItem4UnitAction.class);
	private ItemUnitDetailService	service;
	private UnitService				unitService;
	private SchoolYearService		schoolYearService;
	private ItemService				itemService;
	private ItemStuDetailService	stuDetailService;
	private PaymentRecordService	payRecordService;

	public void setPayRecordService(PaymentRecordService payRecordService) {
		this.payRecordService = payRecordService;
	}

	public void setStuDetailService(ItemStuDetailService stuDetailService) {
		this.stuDetailService = stuDetailService;
	}

	public void setItemService(ItemService itemService) {
		this.itemService = itemService;
	}

	public void setSchoolYearService(SchoolYearService schoolYearService) {
		this.schoolYearService = schoolYearService;
	}

	public void setService(ItemUnitDetailService service) {
		this.service = service;
	}

	public void setUnitService(UnitService unitService) {
		this.unitService = unitService;
	}
	
	@Override
	protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//rows=10&page=1
		//sidx	schoolYearNo
		//sord	desc
		String rows = request.getParameter("rows");
		String page = request.getParameter("page");
		String sortCol = request.getParameter("sidx");
		String sortD = request.getParameter("sord");
		int rowsNo = 10;
		try {
			rowsNo = Integer.valueOf(rows);
		} catch (RuntimeException e) {}
		int pageNo = 1;
		try {
			pageNo = Integer.valueOf(page);
		} catch (RuntimeException e) {}
		PageBean<ItemUnitDetail> pageBean = new PageBean<ItemUnitDetail>(pageNo,rowsNo,sortCol,sortD);
		ItemDetailForm detailForm = (ItemDetailForm) form;
		service.findDetailByYearAndUnit(detailForm.getSchoolYearNo(),
				detailForm.getUnitNo(), pageBean);
		renderJson(response, WebUtils.generateJSONByPageBean(pageBean));
		return null;
	}

	public ActionForward get(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			ItemDetailForm detailForm = (ItemDetailForm) form;
			List<ItemUnitDetail> details = service.findDetailByYearAndUnit(
					detailForm.getSchoolYearNo(), detailForm.getUnitNo());
			renderJson(response, WebUtils.generateJSONByCollection(details));
		} catch (Exception e) {
			log.error(e.getMessage());
			renderJson(
					response,
					WebUtils.generateErrorJSON(TEXT_ERROR_MSG_QUERY + " "
							+ e.getMessage()));
		}
		return null;
	}

	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			ItemDetailForm detailForm = (ItemDetailForm) form;
			ItemUnitDetail detail = buildModel(detailForm);
			stuDetailService.findIsExistingPaymentRecordByOverwritedItem(detail.getSchoolYear().getSchoolYearNo(), detail.getUnit().getParentUnit(), detail);
			service.save(detail);
		} catch (Exception e) {
			log.error(e.getMessage());
			renderJson(
					response,
					WebUtils.generateErrorJSON(TEXT_ERROR_MSG_ADD + " "
							+ e.getMessage()));
		}
		return null;
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			ItemDetailForm detailForm = (ItemDetailForm) form;
			ItemUnitDetail detail = buildModel(detailForm);
			stuDetailService.findIsExistingPaymentRecordByOverwritedItem(detail.getSchoolYear().getSchoolYearNo(), detail.getUnit().getParentUnit(), detail);
			service.update(detail);
		} catch (Exception e) {
			log.error(e.getMessage());
			renderJson(
					response,
					WebUtils.generateErrorJSON(TEXT_ERROR_MSG_EDIT + " "
							+ e.getMessage()));
		}
		return null;
	}

	public ActionForward del(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			ItemDetailForm detailForm = (ItemDetailForm) form;
			ItemUnitDetail detail = service.get(detailForm.getItemPaymentNo());
			if(payRecordService.findPaymentRecordByItemPaymentDetail(detail).size()>0){
				throw new BizException("该缴费项存在已支付记录，不予删除！");
			}
			service.delete(detail);
		} catch (Exception e) {
			log.error(e.getMessage());
			renderJson(
					response,
					WebUtils.generateErrorJSON(TEXT_ERROR_MSG_DEL + " "
							+ e.getMessage()));
		}
		return null;
	}

	private ItemUnitDetail buildModel(ItemDetailForm form) {
		ItemUnitDetail detail = new ItemUnitDetail();
		if (form.getItemPaymentNo() != null && form.getItemPaymentNo() != 0) {
			detail = service.get(form.getItemPaymentNo());
		}
		if (detail.getSchoolYear() == null
				|| (detail.getSchoolYear() != null && !detail.getSchoolYear()
						.getSchoolYearNo().equals(form.getSchoolYearNo()))) {
			SchoolYear year = schoolYearService.get(form.getSchoolYearNo());
			detail.setSchoolYear(year);
		}
		if (detail.getUnit() == null
				|| (detail.getUnit() != null && !detail.getUnit().getUnitNo()
						.equals(form.getUnitNo()))) {
			detail.setUnit(unitService.get(form.getUnitNo()));
		}
		if (detail.getItem() == null
				|| (detail.getItem() != null && !detail.getItem().getItemNo()
						.equals(form.getItemNo()))) {
			//1. when item changed, check this payment item if exists paid record
			if(detail.getItem()!=null&&payRecordService.findPaymentRecordByItemPaymentDetail(detail).size()>0){
				throw new BizException("该缴费项存在已支付记录，不予修改！");
			}
			
			//2. when item changed, check if exists same payment item.
			Item item = itemService.get(form.getItemNo());
			List<ItemUnitDetail> itemDetails = service.findDetailByYearAndUnit(detail.getSchoolYear().getSchoolYearNo(), detail.getUnit().getUnitNo());
			if(itemDetails!=null){
				for (ItemUnitDetail itemUnitDetail : itemDetails) {
					if(itemUnitDetail.getItem()!=null&&itemUnitDetail.getItem().equals(item)){
						throw new BizException("已存在相同缴费项！");
					}
				}
			}
			detail.setItem(item);
		}
		buildModel(form, detail);
		return detail;
	}
	
}
